'use strict';

const { readdirSync } = require('fs')
const Sequelize = require('sequelize')
const define = require('../lib/sequelize-define')
const config = require('../config')

const sequelize = new Sequelize(Object.assign({ define },
    config.mysql.sophic
))


/**
 * import all models
 * @param  {Object}   result
 * @param  {String}   file
 * @return {Object}
 */
const database = readdirSync(`${__dirname}/sophic`)
    .filter(function(file) {
        return file.indexOf('.') !== 0
    })
    .reduce(function(result, file) {
        const model = sequelize['import'](`${__dirname}/sophic/${file}`)
        const key = model.name.replace(/^\S/, s => s.toUpperCase())
        result[key] = model
        return result
    }, {})


/**
 * create association and set auto write operation logs
 * @param  {String} name
 * @return {NULL}
 */
Object
    .keys(database)
    .forEach(function(name) {
        const model = database[name]

        if ('associate' in model) {
            model.associate(database)
        }
    })

database.sequelize = sequelize
database.Sequelize = Sequelize


module.exports = database